package com.gandong8.trace.tool.config.mysql;

import com.baomidou.mybatisplus.extension.plugins.handler.TableNameHandler;
import lombok.extern.slf4j.Slf4j;

//@Component
@Slf4j
//Mybatis-plus使用TableNameHandler分表
//也可以使用sharding-jdbc，但是使用它需要引入额外的jar包。
public class MybatisTableParser implements TableNameHandler {
    private static ThreadLocal<Integer> userIdThreadLocal = new ThreadLocal<>();

    public static void setUserId(Integer userId) {
        userIdThreadLocal.set(userId);
    }
    private static Integer getUserId() {
        return userIdThreadLocal.get();
    }

    //根据用户id取模分表
    @Override
    public String dynamicTableName(String sql, String tableName) {
        Integer userId = getUserId();
        if (userId == null) {
            throw new RuntimeException("userId is null");
        }
        Integer mod = 3;
        String suffix = String.valueOf(userId % mod);
        //清除ThreadLocal的里值，防止线程复用出现问题
        userIdThreadLocal.set(null);
        return tableName + "_" + suffix;
    }
}
